<script setup lang="ts">
// 引入必要的模块和组件
import { AnswerService } from "@/service/Answer";
import { QuestionService } from "@/service/Question";
import { UserService } from "@/service/UserService";
import Tabs from 'primevue/tabs';
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import AppFooter from "../../layout/AppFooter.vue";
import { CommonService } from "../common";
import ConfirmDialog from "../ConfirmDialog.vue";

// 定义引用变量
const confirmDialog = ref<InstanceType<typeof ConfirmDialog>>();
const dialogMessage = ref("正在进行AI智能分析");

const route = useRoute();
const router = useRouter();
const params = ref({
    sn: "",
    isMe: false,
});

// 定义用户和学生信息
const currentUser = ref({
    name: "",
    sn: "",
    role: 0,
});
const student = ref({
    Name: "",
    Sn: "",
    Role: 0,
});

// 定义问题列表、当前模板和模板列表
const QuestionList = ref<{ question: string; answer: string }[]>([]);
const currentTemplate = ref({
    Id: 0,
    Label: "",
    Kind: 0,
    Desc: "",
    Questions: [] as string[],
});
const templateList = ref<{
    Id: number;
    Label: string;
    Kind: number;
    Desc: string;
    Questions: string[];
}[]>([]);

// 加载状态
const isLoading = ref(false);

// 挂载时执行的逻辑
onMounted(async () => {
    try {
        isLoading.value = true;
        // 获取授权信息
        const authorizationStr = localStorage.getItem("Authorization");
        const payload = CommonService.parseJwtPayload(authorizationStr);
        if (!payload) {
            router.push({ name: "login" });
            return;
        }
        currentUser.value = payload;

        // 获取路由参数
        const snStr = String(route.params.sn);
        params.value.sn = snStr;
        params.value.isMe = snStr === currentUser.value.sn;

        // 查询用户信息
        const userInfoResult = await UserService.getUserInfo(snStr);
        handleResult(userInfoResult, "查询用户信息失败");

        student.value = userInfoResult.Data;
        document.title = `${student.value.Name} 专访`;

        // 获取所有模板
        await getAllTemplate();
    } catch (error) {
        alert("查询用户或模板出错");
    } finally {
        isLoading.value = false;
    }
});

// 统一处理结果
const handleResult = (result: any, errorMessage: string) => {
    if (result.Code !== 1000) {
        alert(errorMessage);
        throw new Error(result.Title);
    }
    if (result.Data.length === 0) {
        alert(errorMessage);
        throw new Error("暂无数据");
    }
};

// 打开确认对话框
const openDialog = () => {
    confirmDialog.value?.open();
};
const closeDialog = () => {
    confirmDialog.value?.cancelFun();
};

// 获取所有模板
const getAllTemplate = async () => {
    try {
        isLoading.value = true;
        const result = await QuestionService.getAllTemplate();
        handleResult(result, "查询访谈模板失败");

        templateList.value = result.Data.map((item) => ({
            ...item,
            Questions: JSON.parse(item.Questions),
        }));

        // 默认选中第一个模板
        if (templateList.value.length > 0) {
            onTemplateSelect(templateList.value[0]);
        }
    } catch (error) {
        alert("查询访谈模板出错:" + error);
    } finally {
        isLoading.value = false;
    }
};

// 选择模板时的处理函数
const onTemplateSelect = (item: typeof templateList.value[0]) => {
    QuestionList.value = item.Questions.map((question) => ({
        question,
        answer: "",
    }));
    currentTemplate.value = item;
};

// 保存答案
const saveAnswer = async () => {
    try {
        openDialog();
        const requestBody = JSON.stringify(QuestionList.value);
        const result = await AnswerService.saveUserAnswerList(
            student.value.Sn,
            currentTemplate.value.Id,
            requestBody
        );
        closeDialog();
        handleResult(result, "保存答案失败");
        router.push({ path: `/userAnalysis/${student.value.Sn}` });
    } catch (error) {
        closeDialog();
        alert("saveAnswer 出错:" + error);
    }
};
</script>

<style scoped>
textarea:focus {
    background-color: rgb(194, 221, 193);
}

.loading {
    text-align: center;
    margin-top: 20px;
    font-size: 18px;
    color: white;
}

.student-info {
    text-align: center;
    font-size: 18px;
    color: rgb(3, 107, 49);
}
</style>

<template>
    <div class="bg-surface-0 dark:bg-surface-900" style="font-size: 24px;">
        <!-- 显示访谈学生信息 -->
        <div v-if="!params.isMe" class="student-info">
            <a :href="`/client/${student.Sn}`" target="_blank">
                {{ student.Name + '&nbsp;&nbsp; 学号:' + student.Sn }}
            </a>
            <hr>
        </div>
        <!-- 模板选择标签页 -->
        <div class="flex justify-between items-center">
            <Tabs value="1">
                <TabList>
                    <Tab :value="index" v-for="(item, index) in templateList" :key="index"
                        @click="onTemplateSelect(item)">
                        {{ item.Label }}
                    </Tab>
                </TabList>
            </Tabs>
        </div>
    </div>
    <!-- 问题列表和输入框 -->
    <div class="flex flex-col p-10 items-center"
        style="background-image: linear-gradient(to top, #09203f 0%, #537895 100%);font-size: 24px;">
        <form style="width: 95%" @submit.prevent="saveAnswer">
            <li v-for="(item, index) in QuestionList" :key="index" style="list-style: none;">
                <div style="color: white">
                    <span style="margin-right: 2rem;">第{{ index + 1 }}问: </span> {{ item.question }}
                </div>
                <textarea rows="2" placeholder="很懒,不回答" required minlength="5"
                    style="outline: none; padding: 15px; border-radius: 0.4rem" class="mt-3 w-full"
                    v-model="item.answer"></textarea>
            </li>
            <!-- 提交按钮 -->
            <Button type="submit" security="info" class="m-5" style="height: 4rem; width: 10rem">
                提交
            </Button>
        </form>
        <!-- 加载状态 -->
        <div v-if="isLoading" class="loading">加载中...</div>
        <!-- 页脚 -->
        <AppFooter style="color: aliceblue"></AppFooter>
    </div>
    <!-- 确认对话框 -->
    <ConfirmDialog :message="dialogMessage" ref="confirmDialog" />
</template>
